<template>
  <div class="admin-container">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="header-left">
        <h1>管理员控制台</h1>
      </div>
      <div class="header-right">
        <span>欢迎, {{ user?.name }}</span>
        <el-button type="primary" plain @click="handleLogout">退出登录</el-button>
      </div>
    </el-header>

    <!-- 主要内容 -->
    <el-main>
      <!-- 添加数据表单 -->
      <el-card class="add-form-card">
        <template #header>
          <div class="card-header">
            <span>添加图书借阅数据</span>
          </div>
        </template>
        
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          size="default"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="借阅日期" prop="borrow_date">
                <el-date-picker
                  v-model="form.borrow_date"
                  type="date"
                  placeholder="选择借阅日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="借阅者" prop="borrower">
                <el-select
                  v-model="form.borrower"
                  placeholder="选择借阅者"
                  style="width: 100%"
                  filterable
                  allow-create
                >
                  <el-option
                    v-for="borrower in existingBorrowers"
                    :key="borrower"
                    :label="borrower"
                    :value="borrower"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="借阅图书" prop="borrowed_book">
                <el-select
                  v-model="form.borrowed_book"
                  placeholder="选择图书"
                  style="width: 100%"
                  filterable
                  allow-create
                >
                  <el-option
                    v-for="book in existingBooks"
                    :key="book"
                    :label="book"
                    :value="book"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图书单价" prop="book_unit_price">
                <el-input-number
                  v-model="form.book_unit_price"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                  placeholder="输入图书单价"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="借阅状态" prop="borrow_status">
                <el-select
                  v-model="form.borrow_status"
                  placeholder="选择借阅状态"
                  style="width: 100%"
                >
                  <el-option
                    v-for="status in borrowStatuses"
                    :key="status"
                    :label="status"
                    :value="status"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="submitForm" :loading="submitting">
                  添加数据
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 数据统计 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ totalRecords }}</div>
              <div class="stat-label">总记录数</div>
            </div>
            <el-icon class="stat-icon" color="#409eff">
              <DataAnalysis />
            </el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ totalBorrowers }}</div>
              <div class="stat-label">借阅者数量</div>
            </div>
            <el-icon class="stat-icon" color="#67c23a">
              <User />
            </el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ averagePrice }}元</div>
              <div class="stat-label">平均价格</div>
            </div>
            <el-icon class="stat-icon" color="#e6a23c">
              <Money />
            </el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ todayRecords }}</div>
              <div class="stat-label">今日新增</div>
            </div>
            <el-icon class="stat-icon" color="#f56c6c">
              <Plus />
            </el-icon>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近添加的数据 -->
      <el-card class="recent-data-card">
        <template #header>
          <div class="card-header">
            <span>最近添加的数据</span>
            <el-button type="text" @click="viewAllData">查看全部数据</el-button>
          </div>
        </template>
        
        <el-table
          :data="recentData"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="borrow_date" label="借阅日期" width="120" />
          <el-table-column prop="borrower" label="借阅者" width="100" />
          <el-table-column prop="borrowed_book" label="借阅图书" min-width="160" />
          <el-table-column prop="book_unit_price" label="图书单价" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriceType(row.book_unit_price)" size="small">
                ¥{{ row.book_unit_price }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="borrow_status" label="借阅状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.borrow_status)" size="small">
                {{ row.borrow_status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="deleteRecord(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataAnalysis, User, Money, Plus } from '@element-plus/icons-vue'
import { user, logout } from '@/stores/auth'
import { 
  bookBorrowData, 
  borrowers, 
  books,
  borrowStatuses,
  stats,
  statsLoading,
  addBookBorrowData,
  deleteBookBorrowData,
  fetchStats,
  initBookBorrowData
} from '@/stores/bookBorrow'

const router = useRouter()
const formRef = ref()
const submitting = ref(false)

// 表单数据
const form = reactive({
  borrow_date: '',
  borrower: '',
  borrowed_book: '',
  book_unit_price: null,
  borrow_status: ''
})

// 验证规则
const rules = {
  borrow_date: [
    { required: true, message: '请选择借阅日期', trigger: 'change' }
  ],
  borrower: [
    { required: true, message: '请输入借阅者', trigger: 'blur' }
  ],
  borrowed_book: [
    { required: true, message: '请输入借阅图书', trigger: 'blur' }
  ],
  book_unit_price: [
    { required: true, message: '请输入图书单价', trigger: 'blur' }
  ],
  borrow_status: [
    { required: true, message: '请选择借阅状态', trigger: 'change' }
  ]
}

// 现有借阅者和图书
const existingBorrowers = computed(() => borrowers.value)
const existingBooks = computed(() => books.value)

// 统计数据 - 使用store中的stats
const totalRecords = computed(() => stats.value.total_records)
const totalBorrowers = computed(() => stats.value.total_borrowers)
const averagePrice = computed(() => stats.value.average_price)
const todayRecords = computed(() => stats.value.today_records)

// 最近数据 - 使用store中的recent_data
const recentData = computed(() => stats.value.recent_data || [])

// 价格类型
const getPriceType = (price) => {
  if (price < 20) return 'info'
  if (price < 50) return 'primary'
  if (price < 100) return 'success'
  return 'warning'
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    '已借出': 'warning',
    '已归还': 'success',
    '逾期': 'danger',
    '丢失': 'info'
  }
  return types[status] || 'primary'
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 调用API添加数据
    await addBookBorrowData(form)
    
    // 刷新统计信息
    await fetchStats()
    
    resetForm()
  } catch (error) {
    console.error('添加数据失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  Object.assign(form, {
    borrow_date: '',
    borrower: '',
    borrowed_book: '',
    book_unit_price: null,
    borrow_status: ''
  })
}

// 删除记录
const deleteRecord = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const success = await deleteBookBorrowData(id)
    if (success) {
      // 刷新统计信息
      await fetchStats()
    }
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}

// 查看全部数据
const viewAllData = () => {
  router.push('/dashboard')
}

// 退出登录
const handleLogout = () => {
  logout()
  router.push('/login')
  ElMessage.success('已退出登录')
}

onMounted(async () => {
  // 设置默认日期为今天
  form.borrow_date = new Date().toISOString().split('T')[0]
  
  // 初始化数据
  await initBookBorrowData()
})
</script>

<style scoped>
.admin-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0;
  color: #e6a23c;
  font-size: 24px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.add-form-card,
.recent-data-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-icon {
  font-size: 32px;
  opacity: 0.8;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 